<?php

/*
This example stores the last few songs played in JSON format. It is also able to
serve the json with a callback, useful if this script is on a different domain
than the one where the website is. Example:

<script type="text/javascript">
function rtw_callback(arrayOfSongs) {
	// do something with the songs
}
</script>
<script type="text/javascript" src="http://example.com/json.php?get&callback=rtw_callback">
</script>
*/

$C = array(
	'jsFile'     => 'nowplaying.js',
	'maxEntries' => 5,
);

require_once 'RTWUtils.class.php';

if (array_key_exists('get', $_GET)) {
	$json = file_get_contents($C['jsFile']);
	if (array_key_exists('callback', $_GET)) $json = $_GET['callback'] . '(' . $json . ')';
	header("Content-Type: text/javascript");
	echo $json;
}
else {
	$song_info = RTWUtils::getInfoFromRequest();

	$last_songs = json_decode(file_get_contents($C['jsFile']), true);
	
	if (!is_array($last_songs)) $last_songs = array();
	elseif (count($last_songs) >= $C['maxEntries']) {
		while (count($last_songs) >= $C['maxEntries']) {
			array_shift($last_songs);
		}
	}

	$last_songs[] = $song_info;

	file_put_contents($C['jsFile'], json_encode($last_songs));
}

?>
